package com.coolw.toolkit.commonspool2;

import com.coolw.toolkit.commonspool2.config.DataSourceConfig;
import com.coolw.toolkit.date.DateUtil;
import lombok.SneakyThrows;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

import java.sql.Connection;
import java.sql.DriverManager;
import java.time.LocalDateTime;

/**
 * 自定义数据库对象连接池工厂，提供对象的创建、借用、归还和销毁等功能
 *
 * @author coolw
 * @date 2025/8/15 10:38
 */
public class DataSourcePooledObjectFactory extends BasePooledObjectFactory<Connection> {

    private final DataSourceConfig config;

    public DataSourcePooledObjectFactory(DataSourceConfig config) {
        this.config = config;
    }

    /**
     * 创建对象
     */
    @Override
    public Connection create() throws Exception {
        return DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
    }

    /**
     * 包装对象
     */
    @Override
    public PooledObject<Connection> wrap(Connection connection) {
        return new DefaultPooledObject<>(connection);
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<Connection> p) throws Exception {
        Connection conn = p.getObject();
        if (conn != null) {
            conn.close();
            System.out.println(getCurrentDateTime() + " 销毁对象:" + conn);
        }
    }

    /**
     * 验证对象
     */
    @SneakyThrows
    @Override
    public boolean validateObject(PooledObject<Connection> p) {
        Connection conn = p.getObject();
        return conn != null && !conn.isClosed();
    }

    private String getCurrentDateTime() {
        return DateUtil.formatLocalDateTime(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss");
    }
}
